//
//  FileCache.m
//  LotteryClient
//
//  Created by Sunyon 14-4-22.
//  Copyright (c) 2014年 CTTC. All rights reserved.
//

#import "FileCache.h"
#import "ZipArchive.h"
#import "BaseType.h"
#import "BaseLog.h"
#import "JSONKit.h"
#import "NSString+BaseFramework.h"

#define kSourceNameKeyAndHtmlUrlValue @"kSourceNameKeyAndHtmlUrlValue"

@interface FileCache ()

@end

@implementation FileCache
DEF_SINGLETON()
static NSString *_cacheDir = nil;
static NSMutableDictionary *_sourceNameKeyAndHtmlUrlValueDic = nil;

- (id)init
{
	if (self = [super init])
	{

	}

	return self;
}

- (NSMutableDictionary *)sourceNameKeyAndHtmlUrlValueDic
{
	if (!_sourceNameKeyAndHtmlUrlValueDic)
	{
		NSString *filePath = [NSString filePathInSelfResourceOrBundle:kSourceNameKeyAndHtmlUrlValue];
		_sourceNameKeyAndHtmlUrlValueDic = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];

		if (!_sourceNameKeyAndHtmlUrlValueDic)
		{
			_sourceNameKeyAndHtmlUrlValueDic = [[NSMutableDictionary alloc] init];
		}

	}

	return _sourceNameKeyAndHtmlUrlValueDic;
}

- (void)setObject:(id)value forKey:(NSString *)key
{
	NSString *oldFileName = [[self sourceNameKeyAndHtmlUrlValueDic] objectForKey:key];
	if (oldFileName && [oldFileName notEmpty])
	{
		[NSString delFileInPath:[self filePathInCacheByName:[oldFileName md5String]]];
	}

	[[self sourceNameKeyAndHtmlUrlValueDic] setObject:value forKey:key];
	[[self sourceNameKeyAndHtmlUrlValueDic] writeToFile:[NSString filePathInSelfResourceWithFileName:kSourceNameKeyAndHtmlUrlValue] atomically:YES];
}

- (void)setCacheDir:(NSString *)cacheDir
{
	_cacheDir = [[NSString cacheDirPath] stringByAppendingPathComponent:cacheDir];
}

- (NSString *)cacheDir
{
	return  [[self class] cacheDir];
}

+ (NSString *)cacheDir
{
	if (!_cacheDir)
	{
		_cacheDir = [[[NSString cacheDirPath] stringByAppendingPathComponent:@"com.caitong.default"] copy];
	}

	if (![NSString isExistsFile:_cacheDir])
	{
		[[NSFileManager defaultManager] createDirectoryAtPath:_cacheDir withIntermediateDirectories:YES attributes:nil error:nil];
	}

	return _cacheDir;
}

- (void)downloadResourceByUrl:(NSString *)urlString
{
	NSString *fileName = [urlString md5String];
	NSString *filePath = [[self cacheDir] stringByAppendingPathComponent:fileName];

	if ([NSString isExistsFile:filePath])
	{
		return;
	}
	dispatch_queue_t queue = dispatch_get_global_queue(
                                                       DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        NSURL *url = [NSURL URLWithString:urlString];
        NSError *error = nil;
        NSData *data = [NSData dataWithContentsOfURL:url options:0 error:&error];

        if(!error)
        {
            [data writeToFile:filePath options:0 error:&error];

            if(!error)
            {
				if ([[[urlString pathExtension] lowercaseString] hasPrefix:@"zip"])
				{
					[self unzipWithFilePath:filePath toTargetFileDir:[filePath stringByDeletingLastPathComponent]];
				}
				else if ([[urlString pathExtension]isEqualToString:@""])
				{
					NSString *jsonStr = [[NSString alloc] initWithBytes:[data bytes]
																 length:[data length]
															   encoding:NSUTF8StringEncoding];
					NSDictionary *dic = [jsonStr objectFromJSONString];
					if ([dic isKindOfClass:[NSDictionary class]])
					{
						NSArray *array = [dic allKeys];
						for (NSString *temString in array)
						{
							NSString *value = [dic objectForKey:temString];
                            if ([value isKindOfClass:[NSString class]])
                            {
                                if ([value containsString:@"http:"])
                                {
                                    [self downloadResourceByUrl:value];
                                }
                                [self setObject:value forKey:temString];
                            }
							

						}
					}

				}

            }
            else
            {
                DLog(@"Error saving file %@",error);
            }
        }
        else
        {
            DLog(@"Error downloading zip file: %@", error);
        }

    });

}

- (NSString *)filePathInCacheByName:(NSString *)fileName
{
	NSString *urlString = @"";
	if ([fileName containsString:@"http"])
	{
		urlString = fileName;
	}
	else
	{
		urlString = [[self sourceNameKeyAndHtmlUrlValueDic] objectForKey:fileName];

	}
	return [[[self class] cacheDir] stringByAppendingPathComponent:[urlString md5String]];
}

- (NSString *)stringInFileWithFileName:(NSString *)fileName
{
	NSString *temString = @"";
	NSString *resultString = @"";
	temString = [self filePathInCacheByName:fileName];

	if ([NSString isExistsFile:temString])
	{
		resultString = [[NSString stringWithContentsOfFile:temString
												 encoding:4
													error:nil] copy];
	}
	else
	{
		if ([fileName containsString:@"http"])
		{
			resultString = [[NSString stringWithContentsOfURL:[NSURL URLWithString:fileName]encoding:4 error:nil] copy];
			[resultString writeToFile:temString atomically:YES encoding:4 error:nil];
		}
		else
		{
			resultString = [@"" copy];
		}
	}

	return resultString;
	

}


- (BOOL)unzipWithFilePath:(NSString *)filePath
		  toTargetFileDir:(NSString *)targetDir
{
	BOOL result = NO;
	ZipArchive *za = [[ZipArchive alloc] init];
	if ([za UnzipOpenFile: filePath])
	{
		result = [za UnzipFileTo:targetDir overWrite: YES];
		[za UnzipCloseFile];
	}
    return result;
}


@end
